package com.example.simple_file_chooser;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.HeaderViewListAdapter;
import android.widget.ImageView;
import android.widget.TextView;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;


/**
 * Created by admin on 2017/8/16.
 */
public class MapViewConf {

    public boolean fakeString;

    public static int autoHide;


    public static void initImgAutoHide(int b) {
        autoHide = b;
    }

    public boolean isFakeEnabled() {
        return fakeString;
    }

    public void setFakeEnabled(boolean fakeString) {
        this.fakeString = fakeString;
    }

    private Map<String, String> vmap = new TreeMap<String, String>();


    private static int defaultImg;

    public static void initDefaultInmg(int pdefaultInmg) {
        defaultImg = pdefaultInmg;
    }

    public Map<String, MapViewConf> confs = new TreeMap<String, MapViewConf>();


    private MapViewConf() {
    }

    public static MapViewConf build() {
        return new MapViewConf();
    }

    private List<String> fieldnames = new ArrayList<String>();

    private Context context;
    private List<Integer> viewsid = new ArrayList<Integer>();

    public static MapViewConf with(Context context) {
        MapViewConf conf = build();
        conf.context = context;
        return conf;
    }

    public String fakeKeyword = "";

    public MapViewConf setFake(String title) {
        fakeKeyword = title;
        return this;
    }

    public MapViewConf addPair(Integer viewid, String fieldname) {
        fieldnames.add(fieldname);
        viewsid.add(viewid);
        return this;
    }

    public MapViewConf addPair(String fieldname, Integer viewid) {
        fieldnames.add(fieldname);
        viewsid.add(viewid);
        return this;
    }


    public Object item;
    private View convertView;

//
//    public MapViewConf source(Object item, androidx.core.app.Fragment convertView) {
//        this.item = item;
//        this.convertView = convertView.getView();
//        return this;
//    }

    public MapViewConf source(Object item, Fragment convertView) {
        this.item = item;
        this.convertView = convertView.getView();
        return this;
    }

    public MapViewConf source(Object item, Activity convertView) {
        this.item = item;
        this.convertView = convertView.getWindow().getDecorView();
        return this;
    }

    public MapViewConf source(Object item, View convertView) {
        this.item = item;
        this.convertView = convertView;
        return this;
    }

    int viewlayoutid;

    public int getViewlayoutid() {
        return viewlayoutid;
    }

    public MapViewConf source(int viewlayout) {
        viewlayoutid = viewlayout;
        return this;
    }

    public MapViewConf source(int viewlayout, MapViewConf conf) {
        viewlayoutid = viewlayout;

        confs.put(viewlayoutid + "", conf);
        return this;
    }

    public void toMap() {
        if (item instanceof Map) {
            int id;
            Map map = (Map) item;
            for (int i = 0; i < this.viewsid.size(); i++) {
                id = this.viewsid.get(i);
                View view = convertView.findViewById(id);
                if (view != null) {

                    if (view instanceof TextView) {

                        String name = fieldnames.get(i);

                        map.put(name, ((TextView) view).getText().toString());
                    }
                }
            }
        }

    }


    public MapViewConf toView() {
        try {


//            if (fieldnames.size() == 0 && viewsid.size() == 0) {
//                link();
//                return;
//            }
            String name;
            Object value = null;
            String textepr = "";
            if (item instanceof Map) {
                Map<String, Object> items = (Map<String, Object>) item;
                Map<String, Object> perItem = (Map<String, Object>) item;
                for (int i = 0; i < this.fieldnames.size(); i++) {
                    int idx = -1;
                    name = this.fieldnames.get(i);
                    String n = name;
                    if (name.contains(":")) {

                        idx = name.indexOf(":");

                        textepr = ":" + name.substring(idx + 1);
                    } else {
                        textepr = "";
                    }
                    String[] names = n.split("-");
                    for (int ix = 0; ix < names.length; ix++) {
                        String nnode = names[ix];
                        if (perItem.containsKey(nnode.split(":")[0])) {
                            value = perItem.get(nnode.split(":")[0]);
                            if (value == null) {
                                value = "";
                            }
                            if (idx != -1) {
                                value = nnode.substring(idx + 1).replace("%s", value.toString());
                            }
                            if (ix == names.length - 1) {
                                if (value != null) {
                                    findAndBindView(convertView, perItem, nnode, nnode, value, i);
                                    perItem = (Map<String, Object>) item;
                                    break;
                                }

                            } else {
                                if (value instanceof Map) {
                                    perItem = (Map<String, Object>) value;
                                    continue;
                                } else {
                                    continue;
                                }
                            }

                        }

                    }


                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }

    private void fakeList() {
        setView(item, item, "", "", convertView, convertView);
    }


    protected boolean findAndBindView(View convertView, Object item,
                                      String name, String splitname, Object value, int fieldpos) {
        if (value == null) {
            throw new IllegalArgumentException(
                    "check the 'value' data:ensure it is not null.thanq");
        }
        int theViewId = fieldpos;
        int viewid = this.viewsid.get(theViewId);
        if (viewid == -1) {
            return false;
        } else {
            View theView = convertView.findViewById(viewid);

            return setView(item, value, name, splitname, convertView, theView);
        }

    }

    @Deprecated
    public MapViewConf fields(String... fields) {
        fieldnames.clear();
        fieldnames.addAll(Arrays.asList(fields));
        return this;
    }



    String jsonpath;

    public void setJsonpath(String jsonpath) {
        this.jsonpath = jsonpath;
    }

    public String getJsonpath() {
        return jsonpath;
    }

    private void toMapInner(Map map, View view, Object o) {
        if (view instanceof TextView) {
            String text = ((TextView) view).getText().toString();
            if (text != null) {
                map.put(o.toString(), text);
            }
        }
    }



    Map<String, Map> mSwitchcase = new TreeMap<String, Map>();

    public MapViewConf conf(MapViewConf mc) {
        confs.put("", mc);
        return this;
    }

    public MapViewConf enbaleFake(boolean b) {
        setFakeEnabled(b);
        return this;
    }

    public static abstract class Tackle {
        public abstract void tackleBefore(Object item, Object value, String name,
                                          View convertView, View theView);

        public abstract void tackleAfter(Object item, Object value, String name,
                                         View convertView, View theView);
    }

    Set<String> resMaps = new TreeSet<String>();

    {
        resMaps.add("mipmap");
        resMaps.add("drawable");
    }


    public MapViewConf addTackle(Tackle tackle) {
        this.tackle = tackle;
        return this;
    }

    Tackle tackle;

    public boolean setView(Object value, final View theView) {
        return setView("", value, "",
                "", theView, theView);
    }

    static int hideWIdth;

    @SuppressLint("ResourceType")
    public boolean setView(Object item, Object value, String name,
                           String splitname, View convertView, final View theView) {

        if (theView == null) {
            return false;
        }

        if (tackle != null) {
            tackle.tackleBefore(item, value, name, convertView, theView);
        }
        if (value != null && value.toString().toLowerCase().equals("null")) {
            value = "";
        }
        String casevalue = "";
        String rawname = name;
//        if (name.contains(":")) {
//            rawname = name.split(":")[0];
//        }

        if (value.toString().contains(".")) {

//        if (mSwitchcase.containsKey(rawname)) {
//            if (mSwitchcase.get(rawname).containsKey(value.toString())) {
//            value = mSwitchcase.get(rawname).get(value.toString()).toString();
//            if (value.toString().contains(".") && value.toString().split("\\.")[0].length() != value.toString().length()) {
//                if (value.toString().contains("com.aliang.auto")) {
//                    value = value.toString().replace("com.aliang.auto.", "");
//                    value = new Integer(RRes.get(value.toString()).getAndroidValue());
//                } else if (value.toString().startsWith("R.")) {
//                    value = new Integer(RResApp.get(value.toString()).getAndroidValue());
//                }
//            }
        }
//            }
//        }
//        if (value instanceof String && value.toString().contains(".") && resMaps.contains(value.toString().split("\\.")[0])
//                && value.toString().split("\\.")[0].length() != value.toString().length()) {
//        if (value.toString().toLowerCase().endsWith(":gone")) {
//            theView.setVisibility(View.GONE);
//            value = value.toString().replace(":gone", "");
//        } else if (value.toString().toLowerCase().endsWith(":invisible")) {
//            theView.setVisibility(View.INVISIBLE);
//            value = value.toString().replace(":invisible", "");
//        } else if (value.toString().toLowerCase().endsWith(":visible")) {
//            theView.setVisibility(View.VISIBLE);
//            value = value.toString().replace(":visible", "");
//        }
//            else {
//
//                theView.setVisibility(View.VISIBLE);
//                value = "R." + value.toString();
//                value = new Integer(RRes.get(value.toString()).getAndroidValue());
////                if (theView instanceof ImageView) {
////                    ((ImageView) theView).setImageResource(((Integer) value).intValue());
////                } else {
////                    theView.setBackgroundResource(((Integer) value).intValue());
////                }
//            }
//        }
        if (name.toString().contains(":")) {
            int idx = name.indexOf(":");
            String epr = name.substring(idx + 1);


            String[] ns = name.toString().split(":");

            if (!(epr.contains("(") && epr.contains(")") && epr.contains("#"))) {
                if (epr.contains("%s")) {
                    value = epr.replaceAll("%s", value.toString());
                }
                if (epr.contains("%s")) {
                    String fepr = epr;
                    int l = -1, r = -1;
                    while ((l = fepr.indexOf("%")) != -1 && (r = fepr.indexOf("%", l + 1)) != -1) {
                        String inner = fepr.substring(l + 1, r);
                        if (vmap.containsKey(inner)) {
                            value = epr.replaceAll("%" + inner + "%", vmap.get(inner).toString());
                        }
                    }
                }

            }
        }

        vmap.put(rawname, value.toString());
//        theView.setVisibility(View.VISIBLE);
        if (value.toString().startsWith("#") && value.toString().length() >= 7) {
            int color = 0;
            Exception ee = null;
            try {
                color = Color.parseColor(value.toString());
            } catch (Exception e) {
                ee = e;
            } finally {
                if (ee == null) {
                    theView.setBackgroundColor(color);
                }
            }
            return true;

        }
        if (theView instanceof WebView) {
            if (value instanceof String) {
                ((WebView) theView).loadData(value.toString(), "text/html;charset=UTF-8", null);
            }
        }
        else if (theView instanceof ImageView) {
            if (value instanceof Integer) {
                ((ImageView) theView).setImageResource(Integer.parseInt(value
                        .toString()));
            } else if (value.getClass() == BitmapDrawable.class) {
                ((ImageView) theView).setImageDrawable((BitmapDrawable) value);
            } else if (value instanceof Drawable) {
                ((ImageView) theView).setImageDrawable((Drawable) value);
            } else if (value instanceof String) {
                if (autoHide != -1) {
                    //simp 判断 value 有值 有值显示 没值不显示
                    if (autoHide != 0) {
                        if (hideWIdth == 0) {
                            hideWIdth = convertView.findViewById(autoHide).getLayoutParams().width;
                        }
                        if (TextUtils.isEmpty((CharSequence) value) /*没图*/ || value.toString().equals("-1") || value.equals("null")) {


                            (convertView.findViewById(autoHide)).getLayoutParams().width = 0;
                        } else {
                            (convertView.findViewById(autoHide)).getLayoutParams().width = hideWIdth;
                        }
                    }
                } else if (defaultImg != 0) {
                    ((ImageView) theView).setImageResource(defaultImg);
                }
                if (!TextUtils.isEmpty(value.toString())) {



//                com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(value.toString(), (ImageView) theView, ImageUtil.getOptions(), ImageUtil.getImageLoadingListener(true));


                }


            }

        } else if (theView instanceof CheckBox) {
            if (value != null && (value.toString().trim().toLowerCase().equals("true") || value.toString().trim().toLowerCase().equals("false"))) {
                ((CheckBox) theView).setChecked(Boolean.parseBoolean(value.toString()));
                ((CheckBox) theView).setVisibility(View.VISIBLE);
            }

        } else if (theView instanceof TextView) {

                if (theView instanceof EditText) {
                    ((TextView) theView)
                            .setHint(value instanceof SpannableStringBuilder ? (SpannableStringBuilder) value
                                    : value.toString());
                } else

                    ((TextView) theView)
                            .setText(value instanceof SpannableStringBuilder ? (SpannableStringBuilder) value
                                    : value.toString());

        } else if (theView instanceof View) {
            if (value instanceof Integer) {
                theView.setBackgroundResource((Integer) value);
            }
        }
        if (tackle != null) {
            tackle.tackleAfter(item, value, name, convertView, theView);
        }

//        ViewInflater.tagrate(theView,theView.getContext());
        return false;
    }


}
